var MISSION_TYPE = {"ycd":2500,"zdb":3000,"ydb":4000,"ylj":7000,"zps":8000}
var MISSION_TYPE_NAME = {"ycd":"待出单","zdb":"在打包","ydb":"已打包","ylj":"已领件","zps":"在派送"}
var COMPLEATE_ORDER_STATUS = "zps" ; //设置派送完成后跳转的路径
app.controller('MissionsCtrl', ['$scope','$state','$stateParams','appFactory','missionFactory','$cordovaBarcodeScanner',function($scope, $state,$stateParams,appFactory,missionFactory,$cordovaBarcodeScanner) {
    appFactory.ready().then(function(){
        $scope.initMissions();
    });
    $scope.doRefresh = function(){
        $scope.initMissions() ;
    };
    $scope.initMissions =function(){
        //替换getAllCountByStatus为getMissionCountFromOrder[2500,3000,4000,7000,8000]
        var status = [2500,3000,4000,7000,8000]; //获取所有状态
        missionFactory.getMissionCountFromOrder(status).then(function(allcount){
            $scope.allMission = allcount;
            if(allcount != 0){
                missionFactory.getCountByStatus(MISSION_TYPE,MISSION_TYPE_NAME).then(function(data){
                    $scope.MissionsType = data;
                }).catch(function(){
                    $scope.$broadcast('scroll.refreshComplete');
                })
            }
        }).catch(function(){
            $scope.$broadcast('scroll.refreshComplete');
        }).finally(function(){
            $scope.$broadcast('scroll.refreshComplete');
        });
    };
    $scope.initMissions();
    $scope.gotoMyMission = function(data){
        $state.go('app.mymission',{status:MISSION_TYPE[data],type:"afljMISSIOIN",orderid:"",title:MISSION_TYPE_NAME[data]}) ;
    };
    //通过扫码进行查找，直接进入详情页
    $scope.scanZbra = function(){
        $cordovaBarcodeScanner
            .scan()
            .then(function(barcodeData) {
                var cancelled = barcodeData.cancelled;
                var result = JSON.parse(barcodeData.text);
                if(!cancelled){
                    var oid = result.OID;
                    var aid = result.AID ;
                    var shopid = result.WID ;
                    if(oid){
                        $state.go('app.missionDetail',{orderid:oid}) ;
                    }else{
                        alert('没有获取到oid');
                    }
                }
            }, function(error) {
                alert("扫码失败，请手动输入");
            });
    };
    //
    $scope.searchMission = function(orderid){
        if(orderid.length<5){
            alert("请至少填写连续的5位数字");
            return ;
        }
        //替换searchMissions为searchMissionFormOrder
        missionFactory.searchMissionFormOrder(orderid).then(function(data){
            if(data.length >= 1){
                $state.go('app.mymission',{stauts:0,type:"mhcx",orderid:orderid,title:"我的任务"});
            }else{
                alert("没有找到要查询的订单");
            }
        });
    }
}]);
app.controller('MyMissionCtrl', ['$scope','$state','$stateParams','appFactory','missionFactory',function($scope, $state,$stateParams,appFactory,missionFactory) {
    var MISSION_TYPE_3 = 3 ;
    var searchOrder = $stateParams;
    appFactory.ready().then(function(){
        $scope.missions();
    });
    $scope.doRefresh = function(){
        $scope.missions() ;
    };
    $scope.page=1;
    $scope.limit=10;
    $scope.array = [];

    //var array = new Array();
    $scope.missions = function(){
        var uid = appFactory.getUserInfo().uid;
        var area = appFactory.globalArea();
        var shopArea = appFactory.shopArea();
        var arrayList = new Array;
        var goodsShop = '' ;
        missionFactory.getMissionInfoGroupByOrderStatus(1,searchOrder).then(function(data){
            async.eachSeries(data,function(eachMission,callback){
                if([6,7,8].indexOf(eachMission.get('type')) >=0){
                    //外卖商品显示果饮店
                    goodsShop = shopArea[eachMission.get('shopId')+""]
                }else{
                    //普通商品，显示分区
                    goodsShop = area[eachMission.get('areaId').areaId+""]
                }
                arrayList.push({orderid:eachMission.get('orderid'),orderInfo:eachMission,address:eachMission.get('address'),goods:eachMission.get('goods'),area:area[eachMission.get('areaId')+""],shop:goodsShop,bookdate:eachMission.get('appointmentTime'),orderStatus:eachMission.get('status')});
                callback(null, arrayList);
            },function(err){
                if(err){
                    console.log(err);
                }else{
                    var status = [] ;
                    status.push(parseInt(searchOrder.status));
                    missionFactory.getMissionCountFromOrder(status).then(function(res) {
                        if (arrayList.length === res) {
                            $scope.loadmore = {more: '没有更多了~'};
                        } else {
                            $scope.loadmore = {more: '加载更多~'};
                        }
                        $scope.$apply(function(){
                            $scope.mymissions=arrayList;
                            $scope.array = arrayList;
                            $scope.title =$stateParams.title;
                        });
                    });
                }
            })
        }).catch(function(err){
            console.log(err);
            console.log("err err er ");
            $scope.$broadcast('scroll.refreshComplete');
        }).finally(function(){
            //alert('refreshComplete');
            $scope.title =$stateParams.title;
            //alert($scope.title);
            $scope.$broadcast('scroll.refreshComplete');
        });
    };


    $scope.gotoDetail=function(orderid){
        //window.location.href='#/app/missionDetail/'+orderid;
        $state.go('app.missionDetail',{orderid:orderid}) ;
    }

    $scope.goToFirst = function(orderid){
        //置顶功能：向数据库中更新时间，按时间降序排序
        //alert(orderid);

        missionFactory.updateMissionUpdatedAtOrder(orderid).then(function(data){
            if(data.code === 0){
                $scope.missions();
            }else{
                alert('sorry,失败了');
            }
        });
        /*var uid = appFactory.getUserInfo().uid;
        var Mission = AV.Object.extend('Mission');
        var queryMission = new AV.Query(Mission);
        queryMission.equalTo('orderid',orderid);
        queryMission.equalTo('uid',uid+'');
        queryMission.equalTo('status',1);
        queryMission.first().then(function(res){
            res.save({rushTime:new Date()}).then(function(){
                $scope.missions();
            }).catch(function(err){
                console.log(err)
                $scope.missions();
            });
        });
*/
    };

    $scope.getMore = function(){
        var uid = appFactory.getUserInfo().uid;
        var area = appFactory.globalArea();
        var shopArea = appFactory.shopArea();
        var status = [] ;
        status.push(parseInt(searchOrder.status));
        missionFactory.getMissionCountFromOrder(status).then(function(res){
            if($scope.array.length === res){
                $scope.loadmore = {more:'没有更多了~'};
            }else{
                $scope.page++;
                var goodsShop = '' ;
                missionFactory.getMissionInfoGroupByOrderStatus($scope.page,searchOrder).then(function(data){
                    async.eachSeries(data,function(eachMission,callback){
                        if([6,7,8].indexOf(eachMission.get('type')) >=0){
                            //外卖商品显示果饮店
                            goodsShop = shopArea[eachMission.get('shopId')+""]
                        }else{
                            //普通商品，显示分区
                            goodsShop = area[eachMission.get('areaId').areaId+""]
                        }
                        $scope.array.push({orderid:eachMission.get('orderid'),orderInfo:eachMission,address:eachMission.get('address'),goods:eachMission.get('goods'),area:area[eachMission.get('areaId')+""],shop:goodsShop,bookdate:eachMission.get('appointmentTime'),orderStatus:eachMission.get('status')});
                        callback(null, $scope.array);
                    },function(){
                        $scope.$apply(function(){
                            $scope.mymissions = $scope.array;
                            $scope.loadmore = {more:'加载更多~'};
                        });
                    })
                })
            }
        })
    }

    $scope.cancelMission = function(oid){
        var info = {status:MISSION_TYPE_3} ;
        missionFactory.updateMissionInfo(oid,info).then(function(data){
            if(data.code === 0){
                if(confirm('确认取消派送？') == true){
                    $scope.missions() ;
                }else{
                    return ;
                }
            }else{
                alert('出问题了，可以联系客服部或者技术部');
            }
        }).catch(function(err){
            alert('出问题了，可以联系客服部或者技术部');
        });
    }
}]);

app.controller('MissionDetailCtrl', ['$scope','$stateParams','$state','appFactory','$cordovaGeolocation','$ionicActionSheet','$timeout','missionFactory',function($scope, $stateParams,$state,appFactory,$cordovaGeolocation, $ionicActionSheet,$timeout,missionFactory) {
    appFactory.ready().then(function(){
        $scope.missions();
    });
    var orderId = $stateParams.orderid;
    var missionM = AV.Object.extend("Mission");
    var orderM = AV.Object.extend("Order");
    var missionFlowM = AV.Object.extend("MissionFlow");
    var uid = appFactory.getUserInfo().uid;
    var area = appFactory.globalArea();
    var shopArea = appFactory.shopArea();
    var loadSomeOrders = function(){
        $scope.missions() ;
    };
    $scope.doRefresh = function(){
        loadSomeOrders();
    }
    $scope.inDispatching = 0 ;
    $scope.dispatchingSuccessful = 0 ;
    $scope.missions = function(){
        missionFactory.showMissionDetails(orderId).then(function(data){
            if(data.code === 0){
                $scope.inDispatching = data.button_show.inDispatching;
                $scope.dispatchingSuccessful = data.button_show.dispatchingSuccessful;
                $scope.mymissions=data.data;
            }else{
                $scope.mymissions={};
            }
        }).catch(function(){
            alert('sorry，出错了');
        }).finally(function(){
            $scope.$broadcast('scroll.refreshComplete');
        });

        /*async.auto({
            getMissionInfo:function(callback){
                var queryMission = new AV.Query(missionM);
                queryMission.equalTo('uid',uid+"");
                queryMission.equalTo('status',1);
                queryMission.equalTo('orderid',orderId+"");
                queryMission.first().then(function(data){
                    callback(null, data);
                }).catch(function(err){
                    callback(err);
                });
            },
            getOrderInfo:['getMissionInfo',function(callback,results){
                if(results.getMissionInfo){
                    var Order = AV.Object.extend("Order");
                    var queryOrder = new AV.Query('Order');
                    queryOrder.equalTo('orderid',results.getMissionInfo.get('orderid'));
                    queryOrder.first().then(function(data){
                        if(data){
                            if(data.get('status') === 7000){
                                $scope.inDispatching = 1;
                            }
                            if(data.get('status') >= 8000){
                                $scope.inDispatching = 0;
                                $scope.dispatchingSuccessful = 1;
                            }
                            if([6,7,8].indexOf(data.get('type')) >=0){
                                //外卖商品显示果饮店
                                goodsShop = shopArea[data.get('shopId')+""]
                            }else{
                                //普通商品，显示分区
                                goodsShop = area[data.get('areaId')+""]
                            }
                            callback(null, {orderid:orderId,orderInfo:data,address:data.get('address'),goods:data.get('goods'),area:area[data.get('areaId')+""] ,shop:goodsShop,bookdate:results.getMissionInfo.get('appointmentTime')});

                        }else{
                            callback(null, {orderid:"",orderInfo:{},address:{},goods:{},area:{},shop:{},bookdate:new Date()});
                        }
                    });
                }else{
                    callback(null, {orderid:"",orderInfo:{},address:{},goods:{},area:{},shop:{},bookdate:new Date()});
                }
            }],

            final:['getOrderInfo',function(callback,results){
                callback(null, results.getOrderInfo);
            }],
        },function(err,results){
            if(err){
                $scope.mymissions={};
                //alert('更新成功，没有数据');
                $scope.$broadcast('scroll.refreshComplete');
            }else{
                $scope.mymissions=results.final;
                //alert('更新成功');
                $scope.$broadcast('scroll.refreshComplete');
            }
        });*/
    };
    //$scope.missions();
    //开始配送，更改状态和发短信
    $scope.dispatching=function(){
        event = event ? event : window.event;
        var obj = event.srcElement ? event.srcElement : event.target;
        obj.disabled=true;
        var uid = appFactory.getUserInfo().uid;
        var area = appFactory.globalArea();
        var shopArea = appFactory.shopArea();
        //订单编号    orderId
        //变更状态   status === 8000
        $scope.inDispatching = 0;
        $scope.dispatchingSuccessful = 1;
        async.auto({
            getOrderInfo:function(callback){
                var queryOrder = new AV.Query(orderM);
                queryOrder.equalTo('orderid',orderId);
                queryOrder.first().then(function(data){
                    callback(null, data);
                }).catch(function(err){
                    callback(err);
                });
            },
            //获取定位信息
            getLocation:function(callback){
                /*var posOptions = {timeout: 10000, enableHighAccuracy: false};
                 $cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
                 var lat  = position.coords.latitude;
                 var long = position.coords.longitude;
                 callback(null, {code:0,lat:lat,long:long});
                 }).catch(function(err){
                 callback(err);
                 });*/
                callback(null, {code:0,lat:1.0,long:1.0});
            },
            isInFlow:function(callback){
                var queryMissionFlow = new AV.Query(missionFlowM);
                queryMissionFlow.equalTo('orderId',orderId);
                //queryMissionFlow.equalTo('uid',uid+"");
                queryMissionFlow.equalTo('status',1);
                queryMissionFlow.first().then(function(data){
                    if(data){
                        //删除，再插入
                        data.destroy().then(function(){
                            callback(null, {code:0});
                        }).catch(function(err){
                            callback(err);
                        });
                    }else{
                        callback(null, {code:0});
                    }
                }).catch(function(err){
                    console.log(err);
                    callback(null, {code:0});
                });
            },
            changeOrderInfo:['getOrderInfo',function(callback,results){
                var orderInfo = results.getOrderInfo ;
                if(orderInfo){
                    //变更状态
                    if(orderInfo.get('status')===7000){
                        orderInfo.set('status',8000);
                        //向订单表中插入任务流水中的开始时间---开始
                        orderInfo.set('startTime',new Date());
                        //向订单表中插入任务流水中的开始时间---结束
                        orderInfo.save().then(function(){
                            console.log("变更成功");
                            callback(null,{code:0,msg:'变更成功'});
                        });
                    }else{
                        callback({code:1,msg:'核对状态！'});
                    }

                }else{
                    return ;
                }
            }],
            changeMissionInfo:["changeOrderInfo",function(callback,results){
                if(results.changeOrderInfo.code === 0){
                    var queryMission = new AV.Query(missionM);
                    queryMission.equalTo('uid',uid+"");
                    queryMission.equalTo('status',1);
                    queryMission.equalTo('orderid',orderId);
                    queryMission.first().then(function(data){
                        var detail = data.get('detail');
                        detail['status'] = 8000;
                        data.set('detail',detail);
                        data.save().then(function(){
                            callback(null, {code:0});
                        }).catch(function(err){
                            callback(err);
                        });

                    }).catch(function(err){
                        callback(err);
                    });
                }
            }],
            //向missionflow表中插入数据
            insertMissionFlow:["isInFlow","getLocation","changeMissionInfo",function(callback,results){
                if(results.isInFlow.code === 0){
                    var missionFlow = new missionFlowM();
                    missionFlow.set('uid',uid+"");
                    missionFlow.set('orderId',orderId);
                    missionFlow.set('startLocation',[results.getLocation.lat,results.getLocation.long]);
                    missionFlow.set('startTime',new Date());
                    missionFlow.set('status',1);
                    missionFlow.set('syncStatus',1);
                    missionFlow.set('psRebate',results.getOrderInfo.get('psRebate')||1);  //提成
                    missionFlow.set('address',results.getOrderInfo.get('address'));
                    // missionFlow.set('finalAmount',results.getOrderInfo.get('finalAmount')); //应付金额
                    missionFlow.save().then(function(){
                        callback(null, {code:0});
                    });
                }

            }],
            finalFunction:["insertMissionFlow",function(callback,results){

                if(results.insertMissionFlow.code === 0){
                    //更新成功
                    var phone = results.getOrderInfo.get('address').phone;
                    var uName = results.getOrderInfo.get('address').name;
                    console.log(uName);
                    AV.Cloud.requestSmsCode({
                        mobilePhoneNumber: phone,
                        template: "配送通知",
                        orderid:orderId,
                        name: '果然100',
                        uName:uName
                    }).then(function(data){
                        //发送成功
                        callback(null, {code:0,msg:'发送成功'});
                    }, function(err){
                        //发送失败
                        console.log(err);
                        callback(null, {code:1,msg:'发送失败'});
                    });
                    callback(null, {code:0,msg:'发送成功'});
                }else{
                    callback(null, {code:1,msg:'更新失败，短信发送失败'});
                }
            }],

        },function(err,results){
            if(err){
                console.log(err);
            }else{
                if(results.finalFunction.code === 0){
                    $scope.inDispatching = 0;
                    $scope.dispatchingSuccessful = 1;
                }else{
                    $scope.inDispatching =1;
                    $scope.dispatchingSuccessful = 0;
                }
            }
        });
    };
    //短信测试：
    $scope.sendMessage=function(){
        var uid = appFactory.getUserInfo().uid;
        var area = appFactory.globalArea();
        var shopArea = appFactory.shopArea();
        async.auto({
            //获取order信息
            getOrderInfo:function(callback){
                var queryMission = new AV.Query(missionM);
                queryMission.equalTo('uid',uid+"");
                queryMission.equalTo('status',1);
                queryMission.equalTo('orderid',orderId);
                queryMission.first().then(function(data){
                    callback(null, data);
                }).catch(function(err){
                    callback(err);
                });
            },

            getAddress:["getOrderInfo",function(callback,results){
                //根据addrId获取地址信息
                console.log(results.getOrderInfo);

                if(results.getOrderInfo){
                    var orderInfo = results.getOrderInfo.get('detail');
                    callback(null, {orderid:orderId,orderInfo:orderInfo,address:orderInfo.address,goods:orderInfo.goods,area:area[orderInfo.areaId]});
                }else{
                    callback(null, {orderid:"",orderInfo:{},address:{},goods:{},area:{}});
                }
            }],

            final:['getAddress',function(callback,results){
                var phone = results.getAddress.address.phone;
                var uName = results.getAddress.address.name;
                console.log(uName);
                AV.Cloud.requestSmsCode({
                    mobilePhoneNumber: phone,
                    template: "配送通知",
                    orderid:orderId,
                    name: '果然100',
                    uName:uName
                }).then(function(data){
                    //发送成功
                    callback(null, {code:0,msg:'发送成功'});
                }, function(err){
                    //发送失败
                    console.log(err);
                    callback(null, {code:1,msg:'发送失败'});
                });
                //callback(null, {code:0,msg:'发送成功'});
            }],
        },function(err,results){
            if(err){
                console.log(err);
            }else{
                console.log(results.final);
            }
        });
    }
    //配送成功
    $scope.successfully = function(payway,total){
        //window.location.href='#/app/completMission/'+orderId+'/'+payway+'/'+total;
        $state.go('app.completMission',{orderid:orderId,payway:payway,finalAmount:total});
    }

    $scope.Sheet = function() {
        var btnArr=[];

        var hideSheet = $ionicActionSheet.show({
            buttons:[{text:''},{text:'确认'}],
            titleText: '推迟派送',
            cancelText: '取消',
            cancel: function(){
            },
            buttonClicked: function(index) {
                hideSheet();
            }
        });
        $timeout(function() {
            hideSheet();
        }, 5000);
    };

    $scope.appointment = function(){
        //预约时间
        if($scope.showAppointment == 1){
            $scope.showAppointment = 0;
        }else{
            $scope.showAppointment = 1;
        }
    }
    $scope.sureBookdate = function(){
        var yydate = new Date($scope.mymissions.yydate);
        var yyHour = $scope.mymissions.yytime;
        var bookdate = new Date(new Date(yydate).toDateString() +' '+yyHour+':00:00');
        if(bookdate < new Date()){
            alert('亲，时间不能穿越哦');
            return ;
        }
        //将预约时间更新到mission表中
        var info = {appointmentTime:bookdate}
        missionFactory.updateMissionInfo(orderId,info).then(function(res){
            if(res.code === 0){
                alert('重新预约配送时间成功');
            }else{
                alert('预约失败或者订单不可以预约');
            }
            $scope.showAppointment = 0;
        }).catch(function(err){
            alert('预约失败或者订单不可以预约');
            $scope.showAppointment = 0;
        }).finally(function(){
            $scope.mymissions.bookdate = bookdate;
        });
    }
}]);
app.controller('CompletMissionCtrl',['$scope','$stateParams','$state','appFactory','$cordovaGeolocation',function($scope, $stateParams,$state,appFactory,$cordovaGeolocation) {
    var orderId = $stateParams.orderid;
    var payWay = $stateParams.payway;   //支付方式
    var finalAmount = $stateParams.finalAmount;      //总金额
    var loadSomeOrders = function () {
        $scope.init();
    };
    $scope.doRefresh = function () {
        loadSomeOrders();
    }
    var uid = appFactory.getUserInfo().uid;
    var missionM = AV.Object.extend("Mission");
    var orderM = AV.Object.extend("Order");
    var missionFlowM = AV.Object.extend("MissionFlow");
    var Order = AV.Object.extend("Order");
    $scope.init = function () {
        var queryOrder = new AV.Query(Order);
        queryOrder.equalTo('orderid', orderId);
        queryOrder.first().then(function(data){
            if (data) {
                if (data.get('status') != 8000) {
                    $scope.complete = 0;
                } else {
                    $scope.complete = 1;
                }
                //alert('更新成功，没有数据'+data.get('detail').status);
                $scope.$broadcast('scroll.refreshComplete');
            } else {
                $scope.complete = 0;
                //alert('更新成功');
                $scope.$broadcast('scroll.refreshComplete');
            }
        }).catch(function(err){
            console.log(err);
            alert('没有找到订单');
        });

    };
    $scope.init();

    //根据orderId查询出order详细，获取支付方式和支付金额。核对验证
    $scope.completMision = {payway: '', finalAmount: '', hideRealTotal: '', remark: '', realtotal: ''};
    $scope.completMision.payway = payWay;
    if ($scope.completMision.payway === '货到付款') {
        $scope.completMision.finalAmount = finalAmount;
        $scope.completMision.hideRealTotal = false;
    } else {
        $scope.completMision.finalAmount = 0;
        $scope.completMision.hideRealTotal = true;
    }
    $scope.completMision.remark = '';
    console.log($scope.completMision.realtotal);
    //保存完成后需要将订单状态更新到order表和mission表
    //配送成功

    $scope.save2 = function(){
        alert('保存成功');
    }
    $scope.save1 = function () {
        $scope.complete = 0;
        var realtotal = 0;
        var remark = $scope.completMision.remark;
        if ($scope.completMision.hideRealTotal === true) {
            //是微信支付，则实际收款为0
            realtotal = 0;
        } else {
            if (!$scope.completMision.realtotal) {
                realtotal = $scope.completMision.finalAmount;
            } else {
                realtotal = $scope.completMision.realtotal;
            }
        }

        async.auto({
            //更新order表
            updateOrder: function (callback) {
                //console.log(111111);
                var queryOrder = new AV.Query(orderM);
                queryOrder.equalTo('orderid', orderId);
                queryOrder.first().then(function (data) {
                    if (data) {
                        data.set('status', 9000);
                        //向订单表中插入任务流水中的数据---开始
                        data.set('endTime',new Date());
                        data.set('realAccount', realtotal+'');
                        data.set('psremark', remark);
                        //向订单表中插入任务流水中的数据---结束
                        data.set('syncStatus', 2);
                        data.save().then(function () {
                            callback(null, {code: 0, orderInfo: data});
                        }).catch(function (err) {
                            callback(err);
                        });
                    } else {
                        callback(null, {code: 1, orderInfo: data});
                    }
                });
            },
            updateMission: function (callback) {
                //console.log(2222);
                var queryMission = new AV.Query(missionM);
                queryMission.equalTo('orderid', orderId);
                queryMission.equalTo('uid', uid + "");
                queryMission.equalTo('status', 1);
                queryMission.first().then(function (data) {
                    if (data) {
                        var detail = data.get('detail');
                        detail['status'] = 9000;
                        data.set('status', 0);
                        data.set('detail', detail);
                        data.set('syncStatus', 1);
                        data.save().then(function () {
                            callback(null, {code: 0});
                        }).catch(function (err) {
                            callback(err);
                        })
                    } else {
                        callback(null, {code: 1});
                    }
                });
            },
            //获取定位信息
            getLocation: function (callback) {
                /*var posOptions = {timeout: 10000, enableHighAccuracy: false};
                 $cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
                 var lat  = position.coords.latitude;
                 var long = position.coords.longitude;
                 callback(null, {code:0,lat:lat,long:long});
                 }).catch(function(err){
                 callback(err);
                 });*/
                callback(null, {code: 0, lat: 1.0, long: 1.0});
            },
            updateFlow: ["updateOrder", "updateMission", "getLocation", function (callback, results) {
                //if(results.isInFlow.code === 0){

                //console.log(333333333);
                var queryFlow = new AV.Query(missionFlowM);
                queryFlow.equalTo('orderId', orderId);
                queryFlow.equalTo('status', 1);
                queryFlow.first().then(function (data) {
                    //console.log('////////////')
                    if (data) {
                        data.set('endLocation', [results.getLocation.lat, results.getLocation.long]);
                        data.set('endTime', new Date());
                        data.set('uid', uid + "");
                        data.set('realAccount', realtotal+'');
                        if(data.get('syncStatus') === 1){
                            data.set('syncStatus', 1);
                        }else{
                            data.set('syncStatus', 2);
                        }
                        data.set('remark', remark);
                        data.save().then(function () {
                            callback(null, {code: 0});
                        }).catch(function(err){
                            console.log(err);
                            //console.log('------------------')
                        });
                    }else{
                        callback(null, {code: 0});
                        //console.log('==========')
                    }
                });
                //}
            }],
            updateCourier: ['updateFlow', function (callback, results) {
                //console.log(4444444);
                if (results.updateFlow.code === 0) {
                    //更新快递员信息表
                    //console.log(results.updateOrder.orderInfo);
                    var Courier = AV.Object.extend("Courier");
                    var query = new AV.Query(Courier);
                    var updateRefereeUser = 0;
                    query.get(uid + "").then(function (res) {
                        if (results.updateOrder.orderInfo.get('payway') === '货到付款') {
                            finalAmount = results.updateOrder.orderInfo.get('finalAmount');
                        }else{
                            finalAmount = 0 ;
                        }
                        var list = {};
                        if ([7, 8].indexOf(results.updateOrder.orderInfo.get('type')) >= 0) {
                            //alert("非普通商品");
                            //包月和营销商品
                            //alert('非普通商品');
                            if (results.updateOrder.orderInfo.get('refereeUser') === (uid + '')) {
                                //营销和配送为同一人
                                list = {
                                    tdExpressRebate: parseFloat(res.get('tdExpressRebate')) + parseFloat(results.updateOrder.orderInfo.get('psRebate')|1),
                                    tmExpressRebate: parseFloat(res.get('tmExpressRebate')) + parseFloat(results.updateOrder.orderInfo.get('psRebate')|1),
                                    tdExpress: parseFloat(res.get('tdExpress')) + 1,
                                    tmExpress: parseFloat(res.get('tmExpress')) + 1,
                                    tdMarketingRebate: parseFloat(res.get('tdMarketingRebate')) + parseFloat(results.updateOrder.orderInfo.get('yxRebate')),
                                    tdMarketing: parseFloat(res.get('tdMarketing')) + 1,
                                    tmMarketing: parseFloat(res.get('tmMarketing')) + 1,
                                    tmMarketingRebate: parseFloat(res.get('tmMarketingRebate')) + parseFloat(results.updateOrder.orderInfo.get('yxRebate')),
                                    tdCash: parseFloat(res.get('tdCash')) + parseFloat(finalAmount)
                                }
                            } else {
                                //不是同一个人，需要向营销人员的账户填写上营销提成
                                list = {
                                    tdExpressRebate: parseFloat(res.get('tdExpressRebate')) + parseFloat(results.updateOrder.orderInfo.get('psRebate')|1),
                                    tmExpressRebate: parseFloat(res.get('tmExpressRebate')) + parseFloat(results.updateOrder.orderInfo.get('psRebate')|1),
                                    tdExpress: parseFloat(res.get('tdExpress')) + 1,
                                    tmExpress: parseFloat(res.get('tmExpress')) + 1,
                                    tdCash: parseFloat(res.get('tdCash')) + parseFloat(finalAmount)
                                }
                                //alert('非普通商品,添加tdExpress');
                                updateRefereeUser = 1;
                            }
                        } else  {
                            //外卖订单，需要给派送提成
                            list = {
                                tdExpressRebate: parseFloat(res.get('tdExpressRebate')) + parseFloat(results.updateOrder.orderInfo.get('psRebate')||1),
                                tmExpressRebate: parseFloat(res.get('tmExpressRebate')) + parseFloat(results.updateOrder.orderInfo.get('psRebate')||1),
                                tdExpress: parseFloat(res.get('tdExpress')) + 1,
                                tmExpress: parseFloat(res.get('tmExpress')) + 1,
                                tdCash: parseFloat(res.get('tdCash')) + parseFloat(finalAmount)
                            }
                            //alert('普通商品,添加tdExpress 1');
                        } //else {
                        //    //普通订单没有提成，只计件
                        //    list = {
                        //        tdExpress: parseFloat(res.get('tdExpress')) + 1,
                        //        tmExpress: parseFloat(res.get('tmExpress')) + 1,
                        //        tdCash: parseFloat(res.get('tdCash')) + parseFloat(finalAmount)
                        //    }
                        //    //alert('普通商品,添加tdExpress 2');
                        //}
                        res.save(list).then(function () {
                            callback(null, {code: 0, updateRefereeUser: updateRefereeUser});
                        }).catch(function (err) {
                            callback(err);
                        });
                    }).catch(function (err) {
                        console.log(err);
                        callback(err)
                    })
                }
            }],
            updateCourier2: ['updateCourier', function (callback, results) {
                //console.log(5555555);
                if (results.updateCourier.updateRefereeUser === 1) {
                    var Courier = AV.Object.extend("Courier");
                    var query = new AV.Query(Courier);
                    var updateRefereeUser = 0;
                    query.get(results.updateOrder.orderInfo.get('refereeUser') + "").then(function (res) {
                        var list = {
                            tdMarketingRebate: parseFloat(res.get('tdMarketingRebate')) + parseFloat(results.updateOrder.orderInfo.get('yxRebate')),
                            tdMarketing: parseFloat(res.get('tdMarketing')) + 1,
                            tmMarketing: parseFloat(res.get('tmMarketing')) + 1,
                            tmMarketingRebate: parseFloat(res.get('tmMarketingRebate')) + parseFloat(results.updateOrder.orderInfo.get('yxRebate')),
                        }
                        res.save(list).then(function () {
                            //console.log(3333);
                            callback(null, {code: 0});
                        }).catch(function (err) {
                            callback(err);
                        });
                    });

                } else {
                    callback(null, {code: 0});
                }
            }],
        }, function (err, results) {
            if (err) {
                //$state.go('app.mymission',{status:MISSION_TYPE[COMPLEATE_ORDER_STATUS],type:"afljMISSIOIN",orderid:""});
                alert('出错了，请正常派单。结单有异常可联系主管或者技术部！');
                console.log(err);
            }else{
                //alert('派送成功！');
                //$state.go('app.missions');
            }

            //console.log(6666);
            //window.location.href='#/app/mymission';
            //$state.go('app.mymission',{status:MISSION_TYPE[data],type:"afljMISSIOIN",orderid:"",title:MISSION_TYPE_NAME[data]}) ;
            //$state.go('app.mymission',{status:MISSION_TYPE[COMPLEATE_ORDER_STATUS],type:"afljMISSIOIN",orderid:"",title:MISSION_TYPE_NAME[COMPLEATE_ORDER_STATUS] });
        });
    };
    $scope.save = function(){
        event = event ? event : window.event;
        var obj = event.srcElement ? event.srcElement : event.target;
        obj.disabled=true;
        if($scope.completMision.hideRealTotal === true){
            //微信支付
            alert('派送完成');
            $scope.save1();
            $state.go('app.missions');
            return;
        }else{
            if($scope.completMision.finalAmount === $scope.completMision.realtotal ){
                if(confirm('确认派送成功？') == true){
                    $scope.save1();
                    $state.go('app.missions');
                }else{
                    return ;
                }
            }else{
                if($scope.completMision.remark != ''){
                    if(confirm('应收款和实际收款不等，确认派送成功？') == true){
                        $scope.save1();
                        $state.go('app.missions');
                    }else{
                        return ;
                    }
                }else{
                    alert('请填写备注!');
                    obj.disabled=false;
                    return ;
                }

            }
        }
    };
    $scope.alipay = function () {
        var $modal = angular.element("#alipay");
        //progress.start();
        $modal.modal();

    };
    var remarkText = {
        cancel:'用户取消订单',
        daofu:'到付',
        yifu:'已付',
        other:'其他'
    };
    $scope.remarkQuickly = function(args){
        $scope.completMision.remark = remarkText[args];
    }

}]);
